package com.example.myapp.Activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.bumptech.glide.Glide;
import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.CommentAdaper;
import com.example.myapp.ADO.MyDialog;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Comment;
import com.example.myapp.Model.Fensi;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.loopj.android.image.SmartImageView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class ArticleBody extends AppCompatActivity {

 private    List<Comment>  commentList;

    private CircleImageView icon;
    private TextView artbody_username;
    private TextView artbody_content;
    private SmartImageView artbody_image;
    private TextView artbody_zancount;
    private TextView artbody_pinluncount;
    private TextView artbody_zhuanfancount;
    private TextView  artbody_shouchangcount;
    private Button art_zan;
    private TextView art_zankey;
    private Button art_zhuanfa;
    private TextView art_zhuanfakey;
    private Button art_shangcang;
    private TextView    art_shouchangkey;
    private TextView    artbody_guanzhu;
    private LinearLayout artlist_body;
    private  List<String> gzlist=new ArrayList<>();//关注
     private    String authorId;
    private TextView    zhuanfa_content;
    private   String ArticleID;
    private   String UserID;
    private  EditText artpinlun_content;
    private TextView  art_fabu;
     private ShapeLoadingDialog shapeLoadingDialog;
    private ListView lsitnew ;
    private Article article;
    private HorizontalScrollView scll;
    private LinearLayout ll;
    private List<String> listimgs = new ArrayList<String>();//创建图片url数组
    private TextView   paviews;
    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:{

                    initguanzhu();//得到关注的用户1
                    initview();//初始化页面并且得到用户ID
                    initpinlun();
                    initzan();
                    initzhuanfa();
                    initshoucang();
                    queryartAuthor();
                    queryALLComment(ArticleID);
                }break;
                case 1: {
                    clearcomment(ArticleID);
                } break;

            }
        }

    };









    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_article_body);
         icon =findViewById(R.id.artbody_icon);
        scll =findViewById(R.id.scll);
        ll=findViewById(R.id.ll);
        lsitnew = findViewById(R.id.artlistview);
        paviews= findViewById(R.id.paviews);
        artlist_body= findViewById(R.id.artlist_body);
         artbody_username =findViewById(R.id.artbody_username);
         artbody_content =findViewById(R.id.artbody_content);
         artbody_image=findViewById(R.id.artbody_image);
         artbody_zancount =findViewById(R.id.artbody_zancount);
        artbody_pinluncount =findViewById(R.id.artbody_pinluncount);
        artbody_zhuanfancount =findViewById(R.id.artbody_zhuanfancount);
        artbody_shouchangcount =findViewById(R.id.artbody_shouchangcount);
        art_zan=findViewById(R.id.art_zan);
        art_zankey=findViewById(R.id.art_zankey);
        art_zhuanfa=findViewById(R.id.art_zhuanfa);
        art_zhuanfakey=findViewById(R.id.art_zhuanfakey);
        art_shangcang=findViewById(R.id.art_shangcang);
        art_shouchangkey=findViewById(R.id.art_shouchangkey);
        artbody_guanzhu=findViewById(R.id.artbody_guanzhu);
        zhuanfa_content=findViewById(R.id.zhuanfa_content);
          art_fabu=findViewById(R.id.art_fabu);
       artpinlun_content=findViewById(R.id.artpinlun_content);
       ImageView articlebody_back=findViewById(R.id.articlebody_back);
        Intent intent =getIntent();
        ArticleID=intent.getStringExtra("ArticleID");
        Log.e("bbbb","我收到的文章id"+ArticleID);
        Message message=new Message();
        message.what=0;
        handler.sendMessage(message);
        //文本框监听开始，判断昵称是否被占用d0415335f4
        TextWatcher watcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Toast.makeText(getApplicationContext(), "输入之前", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Toast.makeText(getApplicationContext(), "在输入中", Toast.LENGTH_SHORT).show();
                if( artpinlun_content.getText().toString().trim().length()>0){
                  //  art_fabu.setBackgroundColor(Color.parseColor("#0F9C57"));
                    art_fabu.setTextColor(Color.parseColor("#3A70D1"));//
                }else {
                   // art_fabu.setBackgroundColor(Color.parseColor("#E6EFDE"));
                    art_fabu.setTextColor(Color.parseColor("#8E8080"));//
                }

            }
            @Override
            public void afterTextChanged(Editable s) {


            }
        };
        artpinlun_content.addTextChangedListener(watcher);
        //文本框监听结束
        art_fabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                saveComment( artpinlun_content.getText().toString());
            }
        });

        articlebody_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });


        artbody_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否已经关注
                if(artbody_guanzhu.getText().toString().equals("关注")){
                    artbody_guanzhu.setTextColor(Color.parseColor("#CCCCCC"));//橘色
                    artbody_guanzhu.setText("已关注");
                    gzlist.add(authorId);//保存到当前关注数据刷新用，因为后台来不及刷新
                    saveFriend(authorId);//添加好友关联
                }
                else if(artbody_guanzhu.getText().toString().equals("已关注")){
                            gzlist.remove(authorId);
                            artbody_guanzhu.setTextColor(Color.parseColor("#FF5722"));//橘色
                            artbody_guanzhu.setText("关注");
                            clearFriend(authorId);//取消关注
                }
//                    (artlist_guanzhu.getText().toString().equals("删除动态"))
                else {

                    View view = getLayoutInflater().inflate(R.layout.exit_dialog_layout, null);
                    MyDialog mMyDialog = new MyDialog(ArticleBody.this, 0, 0, view, R.style.DialogTheme);
                    TextView exitall = view.findViewById(R.id.exitall);
                    TextView dialog_title = view.findViewById(R.id.dialog_title);
                    TextView exitback = view.findViewById(R.id.exitback);
                    dialog_title.setText("你确定删除吗？");
                    mMyDialog.setCancelable(true);
                    mMyDialog.show();
                    exitall.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            clearArticle(ArticleID);
                        }
                    });
                    exitback.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mMyDialog.dismiss();
                        }
                    });
                }
            }
        });//关注按钮
        art_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (art_zankey.getText().toString().equals("已点赞")){
                    clearzan(ArticleID);
                    int a=  Integer.parseInt( artbody_zancount.getText().toString())  ;
                    a--;
                    artbody_zancount.setText("" + a);
                   art_zan.setBackgroundResource(R.drawable.listdianzan);
                  art_zankey.setText("点赞");
                }else {
                    addzan(ArticleID);
                    int a=  Integer.parseInt( artbody_zancount.getText().toString())  ;
                    a++;
                    artbody_zancount.setText("" + a);
                   art_zan.setBackgroundResource(R.drawable.listdianzan1);
                  art_zankey.setText("已点赞");
                }

            }
        });//点赞按钮

        art_shangcang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (art_shouchangkey.getText().toString().equals("已收藏")){
                    clearshoucang(ArticleID);
                    int a=  Integer.parseInt( artbody_shouchangcount.getText().toString())  ;
                    a--;
                    artbody_shouchangcount.setText("" + a);
                    art_shangcang.setBackgroundResource(R.drawable.artshoucang);
                    art_shouchangkey.setText("收藏");
                }else {
                    addclearshoucang(ArticleID);
                    int a=  Integer.parseInt( artbody_shouchangcount.getText().toString())  ;
                    a++;
                    artbody_shouchangcount.setText("" + a);
                    art_shangcang.setBackgroundResource(R.drawable.artshoucang1);
                    art_shouchangkey.setText("已收藏");
                }

            }
        });//收藏
        art_zhuanfa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if(artlist_zhuanfakey.getText().toString().equals("转发")){
                AlertDialog.Builder builder = new AlertDialog.Builder(ArticleBody.this);
                final   EditText et =new EditText(ArticleBody.this);
                builder.setView(et);
                builder.setTitle("说点什么吧");
                builder.setView(et);
                builder.setPositiveButton("转发",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                addzhuanfaflag(ArticleID);
                                zhuanfa(authorId,article.getContent(),et.getText().toString(),article.getImages());
                                Log.w("aaaa","查询对象："+article.getAuthor().getUsername());

                            }
                        });
                builder.setNegativeButton("取消",null);
                builder.show();
//                 }else {
//                    Toast.makeText(context, "你已经转发过！" , Toast.LENGTH_LONG).show();
//
//                }
            }
        });//转发
        icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (article.getAuthor().getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                    Intent intent = new Intent(ArticleBody.this, Myhome.class);
                   startActivity(intent);
                }else {
                    Intent intent = new Intent(ArticleBody.this, Friendshome.class);
                    intent.putExtra("userID", article.getAuthor().getObjectId());
                    intent.putExtra("iconUrl",article.getAuthor().getIcon().getUrl());
                    intent.putExtra("userName",article.getAuthor().getUsername());
                    if (article.getAuthor().getShow()!=null){
                        intent.putExtra("jianJie",article.getAuthor().getShow());
                    }
                    startActivity(intent);
                }
            }
        });



    }


    /**添加多对多文章转发*/
    private void zhuanfa(String articleAuthor, String content, String input, BmobFile imgage){
        openLoading();
        Article zhuanfa=new Article();
        zhuanfa.setZhuanfaContent(input);
        zhuanfa.setContent("@"+articleAuthor+":"+content);
        zhuanfa.setImages(imgage);
        //添加一对一关联，用户关联帖子
        zhuanfa.setAuthor(BmobUser.getCurrentUser(User.class));
        zhuanfa.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "转发帖子成功！" + s);
                    saveComment(input);
                    Toast.makeText(getApplicationContext(),"转发成功" , Toast.LENGTH_LONG).show();
                    closeLoading();
                } else {
                    Log.w("aaaa", "转发帖子失败！" + e.getMessage());
                    Toast.makeText(getApplicationContext(),"转发失败" , Toast.LENGTH_LONG).show();
                    closeLoading();
                }
            }
        });

    }//不带照片的

    /**添加多对多文章转发标志*/
    //填写被当前用户要关注的用户id
    private void addzhuanfaflag(String userObjId) {

        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被点赞的文章并且给上Id
            article.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user);//装进去当前用户;
            article.setZhuanfa(relation);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加转发成功");
                    closeLoading();
                    } else {
                        Log.i("aaaa", "添加转发失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }
    /**添加多对多文章转发标志*/



    public void onBackPressed() {

        finish();


    }

    /**
     * 添加一对多关联，评论
     */
    private void saveComment( String content) {
        openLoading();
        Article post = new Article();
        post.setObjectId(ArticleID);//测试文本1的文章id
        User user = BmobUser.getCurrentUser(User.class);
        final Comment comment = new Comment();
        comment.setContent(content);
        comment.setArticle(post);//上传文章ID
        comment.setAuthor(user);//上传当前作者名字
        comment.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Log.i("aaaa", "评论发表成功");

                    Collections.reverse(commentList);//倒序
                    commentList.add(comment);
                    artpinlun_content.setText("");
                    Collections.reverse(commentList);//倒序
                    CommentAdaper adapter = new CommentAdaper(ArticleBody.this,commentList,gzlist);//NewAdapterDAO为自定义适配器
                    lsitnew.setAdapter(adapter);
                    closeLoading();
                } else {
                    Log.i("aaaa", "评论发表失败：" + e.getMessage());
                    closeLoading();
                }
            }

        });
    }


    //    输入需要查询被关注的用户有被我关注
    private void initguanzhu(){
        if (BmobUser.isLogin()) {
            BmobQuery<User> query = new BmobQuery<User>();
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            User user = BmobUser.getCurrentUser(User.class);//查自己
            query.addWhereRelatedTo("friend", new BmobPointer(user));
            //包含作者信息
            query.include("user,author,article");
            query.findObjects(new FindListener<User>() {
                @Override
                public void done(List<User> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "详情页面关注个数"+object.size());
                        for (int i=0;i<object.size();i++){
                            gzlist.add(object.get(i).getObjectId());
                        }
                    } else {
                        Log.e("aaaa","查询好友关注"+ e.getMessage());
                    }
                }
            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }


    private  void initview(){

    //查找Person表里面id为6b6c11c537的数据
    BmobQuery<Article> bmobQuery = new BmobQuery<Article>();
    bmobQuery.include("author,zan");
    bmobQuery.getObject(ArticleID, new QueryListener<Article>() {
        @Override
        public void done(Article object,BmobException e) {
            if(e==null){
                if (object!=null){
                article=object;
                Glide.with(getApplicationContext()).load(object.getAuthor().getIcon().getUrl()).into(icon);// CircleImageView.显示网络图片特殊方法
                artbody_username.setText(object.getAuthor().getUsername());
                authorId=object.getAuthor().getObjectId();
                Log.e("bbbb","我查找的文章内容"+object.getContent());
                paviews.setText(""+object.getPageviewNum().intValue());
            //  判断是否是转发的？
                    if (object.getZhuanfaContent() != null) {
                        zhuanfa_content.setVisibility(View.VISIBLE);
                        zhuanfa_content.setText(object.getZhuanfaContent());
                        String[] split = object.getContent().split(":");
                        String str1 = "<font color = '#6795B5'>" + split[0] + ":" + "</font>" + split[1] + "";
                        CharSequence charSequence;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            charSequence = Html.fromHtml(str1, Html.FROM_HTML_MODE_LEGACY);
                        } else {
                            charSequence = Html.fromHtml(str1);
                        }
                        artlist_body.setBackgroundColor(Color.parseColor("#EEEEEE"));
                        artbody_content.setText(charSequence);


                    }else {

                        artbody_content.setText(object.getContent());
                    }


                /**初始化照片*/
                    listimgs = getlisturl(article);//获取图片链接合成数组

                    if (listimgs.size() == 0) {
                       scll.setVisibility(View.GONE);
                    } else {
                        /**--设置宽高*/
                        WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
                        double w = wm.getDefaultDisplay().getWidth() / 1; //获取屏幕宽度分成一份
                        int with = Integer.parseInt(new java.text.DecimalFormat("0").format(w));
                        LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(with, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
                        for (int j = 0; j < listimgs.size(); j++) {
                            /**每个循环填充item_img_horizontal这个布局文件*/
                            View v = getLayoutInflater().inflate(R.layout.item_img_horizontal, null);
                            final SmartImageView imageView = v.findViewById(R.id.item_image);
                            imageView.setId(j);
                            imageView.setImageUrl(listimgs.get(j));
                            final List<String> imgs = listimgs;
                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getApplicationContext(), ShowArryImg.class);
                                    intent.putExtra("pathArry", imgs.toString());
                                    intent.putExtra("index", imageView.getId() + "");
                                    startActivity(intent);
                                }
                            });
                           ll.addView(v, j, params);
                        }

                    }

                artbody_image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ArticleBody.this, Showimage.class);
                        intent.putExtra("imagepath", object.getImages().getUrl());//打开主页
                      startActivity(intent);
                    }
                });


                /**初始化关注*/
                if (gzlist.contains(authorId)){
                    artbody_guanzhu.setText("已关注");
                    Log.w("aaaa","当前用户"+BmobUser.getCurrentUser(User.class).getObjectId());
                    artbody_guanzhu.setTextColor(Color.parseColor("#CCCCCC"));//已经关注的颜色
                }
                if(object.getAuthor().getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                    artbody_guanzhu.setText("删除动态");
                    artbody_guanzhu.setTextColor(Color.parseColor("#FF5722"));//橘色
                }


                Log.w("aaaa", "查询文章成功");
            }else{
                Log.w("aaaa", "查询失败：" + e.getMessage());
            }


                Article p = new Article();
                int num=object.getPageviewNum().intValue();
                num++;
                p.setPageviewNum(num);
                p.update(ArticleID, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e==null){

                        }else{

                        }
                    }

                });
        }
        }
    });

}//初始页面



    //    获取图片数组
    private List<String> getlisturl(Article posts){
        List<String> urlList=new ArrayList<>();
        if(posts.getImages()!=null){
            urlList.add(posts.getImages().getUrl());
        }
        if(posts.getImages2()!=null){
            urlList.add(posts.getImages2().getFileUrl());
        }
        if(posts.getImages3()!=null){
            urlList.add(posts.getImages3().getFileUrl());
        }
        if(posts.getImages4()!=null){
            urlList.add(posts.getImages4().getFileUrl());
        }
        if(posts.getImages5()!=null){
            urlList.add(posts.getImages5().getFileUrl());
        }
        if(posts.getImages6()!=null){
            urlList.add(posts.getImages6().getFileUrl());
        }

        return urlList;

    }








    /**添加一对多粉丝*/
    private void saveFensi(String userID) {
        User user = new User();
        user.setObjectId(userID);//测试文本1的文章id
        final Fensi fensi = new Fensi();
        fensi.setUser(user);
        fensi.setFensi(BmobUser.getCurrentUser(User.class));
        fensi.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "添加粉丝成功！");
                } else {
                    Log.w("aaaa", "添加粉丝成功失败：" + e.getMessage());
                }
            }

        });
    }
    /**删除一对多粉丝*/
    private  void clearFensi(String userID){
        BmobQuery<Fensi> eq1 = new BmobQuery<>();
        eq1.addWhereEqualTo("user",userID);
        BmobQuery<Fensi> eq2 = new BmobQuery<>();
        eq2.addWhereEqualTo("fensi", BmobUser.getCurrentUser(User.class).getObjectId());
        List<BmobQuery<Fensi>> queries = new ArrayList<BmobQuery<Fensi>>();
        queries.add(eq1);
        queries.add(eq2);
        //查询符合整个and条件的人
        BmobQuery<Fensi> addquery = new BmobQuery<Fensi>();
        addquery.and(queries);
        addquery.findObjects(new FindListener<Fensi>() {
            @Override
            public void done(List<Fensi> object, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "查询粉丝成功："+object.get(0).getObjectId() );
                    Fensi p2 = new Fensi();
                    p2.setObjectId(object.get(0).getObjectId());
                    p2.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                Log.w("aaaa", "删除粉丝成功:"+p2.getUpdatedAt());
                            }else{
                                Log.w("aaaa", "删除粉丝失败：" + e.getMessage());
                            }
                        }
                    });

                } else {
                    Log.w("aaaa", "查询粉丝失败："+e.getMessage() );
                }
            }
        });

    }


    /** 添加多对多好友*/
    //填写被当前用户要关注的用户id
    private void saveFriend(String userObjId) {
        openLoading();
        if (BmobUser.isLogin()) {

            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            User user1 = new User();//创建被关注用户并且给上Id
            user1.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user1);//装进去当前用户;
            user.setFriend(relation);
            user.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加好友成功");

                        initview();
                        closeLoading();
                        saveFensi(userObjId);
                    } else {
                        Log.i("aaaa", "添加好友失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }

    /** 删除多对多*/
    //填写被当前用户要关注的用户id
    private void clearFriend(String userObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            User user1 = new User();//创建被关注用户并且给上Id
            user1.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.remove(user1);//装进去当前用户;
            user.setFriend(relation);
            user.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "取消关注成功");
                        //     notifyDataSetChanged();
                        closeLoading();
                        clearFensi(userObjId);
                    } else {
                        Log.i("aaaa", "取消关注失败：" + e.getMessage());
                        closeLoading();
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }











    private void initpinlun(){
    BmobQuery<Comment> query_comment = new BmobQuery<>();
    Article post_comment = new Article();
    post_comment.setObjectId(ArticleID);//测试文章1
    query_comment.addWhereEqualTo("article",new BmobPointer(post_comment));
    query_comment.include("user,author,article");
    query_comment.findObjects(new FindListener<Comment>() {
        @Override
        public void done(List<Comment> object, BmobException e) {
            if (e == null) {
                Log.w("aaaa", "查询评论成功！"+object);
                artbody_pinluncount.setText(""+object.size());

            } else {
                Log.e("aaaa","查询评论失败"+ e.getMessage());
            }
        }
    });
}//初始化统计

private void initzan(){
    BmobQuery<User> query = new BmobQuery<User>();
    Article post = new Article();   // 创建需要查询的文章
    post.setObjectId(ArticleID);
    //friend是User表中的字段，用来存储所有关注的用户
    query.addWhereRelatedTo("zan", new BmobPointer(post));
    query.findObjects(new FindListener<User>() {
        @Override
        public void done(List<User> object, BmobException e) {
            if (e == null) {
                Log.w("aaaa", "文章点赞人数："+object.size());
                artbody_zancount.setText(""+object.size());
                for (int i=0;i<object.size();i++){
//                            如果有自己
                    if (object.get(i).getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                        Log.w("aaaa", "我已经点赞了！"+object.get(i).getUsername());
                        art_zan.setBackgroundResource(R.drawable.listdianzan1);
                        art_zankey.setText("已点赞");
                        return;
                    }else {
                        art_zan.setBackgroundResource(R.drawable.listdianzan);
                        art_zankey.setText("点赞");
                    }

                }
            } else {
                Log.e("aaaa","查询点赞失败"+ e.getMessage());
            }
        }
    });
}//初始化点赞统计

private void initshoucang(){
        BmobQuery<User> query = new BmobQuery<User>();
        Article post = new Article();   // 创建需要查询的文章
        post.setObjectId(ArticleID);
        //friend是User表中的字段，用来存储所有关注的用户
        query.addWhereRelatedTo("likes", new BmobPointer(post));
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "文章点赞人数："+object.size());
                    artbody_shouchangcount.setText(""+object.size());
                    for (int i=0;i<object.size();i++){
//                            如果有自己
                        if (object.get(i).getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                            Log.w("aaaa", "我已经点赞了！"+object.get(i).getUsername());
                            art_shangcang.setBackgroundResource(R.drawable.artshoucang1);
                            art_shouchangkey.setText("已收藏");
                            return;
                        }
                    }
                } else {
                    Log.e("aaaa","查询点赞失败"+ e.getMessage());
                }
            }
        });
    }//初始收藏赞统计

private void initzhuanfa(){
    BmobQuery<User> zhuanfa = new BmobQuery<User>();
    Article post=new Article();
    post.setObjectId(ArticleID);
    zhuanfa.addWhereRelatedTo("zhuanfa", new BmobPointer(post));
    zhuanfa.findObjects(new FindListener<User>() {
        @Override
        public void done(List<User> object, BmobException e) {
            if (e == null) {
                Log.w("aaaa", "文章转发人数："+object.size());
                artbody_zhuanfancount.setText(""+object.size());

                for (int i=0;i<object.size();i++){
//                            如果有自己
                    if (object.get(i).getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                        Log.w("aaaa", "我已经转发了！"+object.get(i).getUsername());
                        art_zhuanfa.setBackgroundResource(R.drawable.listzhuanfa1);
                        art_zhuanfakey.setText("已转发");
                        return;
                    }
                }
            } else {
                Log.e("aaaa","查询转发失败"+ e.getMessage());
            }
        }
    });
}//初始化转发

private void queryartAuthor(){

        // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
        BmobQuery<Article> query = new BmobQuery<>();
        Article post = new Article();
        post.setObjectId("d0415335f4");//测试文章1

        //包含作者信息
//         query.include("author");
            query.findObjects(new FindListener<Article>() {
                @Override
                public void done(List<Article> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "成功找到作者！"+object.get(0).getAuthor().getUsername());

                    } else {
                        Log.e("aaaa","找作者失败"+ e.getMessage());

                    }
                }

            });

    }//得到文章作者


    /**删除文章*/
    private void clearArticle( String  articleId){
        openLoading();
        Article article = new Article();
        article.setObjectId(articleId);
        article.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    Log.w("aaaab:","删除成功"+article.getUpdatedAt());
                  Message message=new Message();
                  message.what=1;
                  handler.sendMessage(message);
                }else{
                    Log.w("aaaab","删除失败：" + e.getMessage());
                }

            }
        });
    }

    /**删除文章*/
    private void clearcomment( String  articleId){
        BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("article",articleId);
        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (e==null){
                    Log.w("aaaa","查找评论正确：" + list.size());
                    if (list.size()>0){
                        list.get(0).delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    Log.w("aaaab:","删除成功");
                                    Message message=new Message();
                                    message.what=1;
                                    handler.sendMessage(message);
                                }else{
                                    Log.w("aaaab","删除失败：" + e.getMessage());
                                }
                            }
                        });
                    }else {
                        Log.w("aaaab","没有评论了 可以退出啦!");
                        closeLoading();
                        Intent intent = new Intent(ArticleBody.this, Main.class);
                        intent.putExtra("page", R.id.today_tab);//打开主页
                        startActivity(intent);
                        finish();
                    }
                } else {
                    Log.w("aaaa","查找评论错误：" + e.getMessage());
                }
            }
        });

    }







    /** 删除多对多*/
    //填写被当前用户要关注的用户id
    private void clearshoucang(String articleObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被关注用户并且给上Id
            article.setObjectId(articleObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.remove(user);//装进去当前用户;
            article.setLikes(relation);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "取消收藏成功");

                        closeLoading();
                    } else {
                        Log.i("aaaa", "取消收藏失败：" + e.getMessage());
                        closeLoading();
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }
    /**添加多对多文章关注*/
    //填写被当前用户要关注的用户id
    private void addclearshoucang(String articleObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被点赞的文章并且给上Id
            article.setObjectId(articleObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user);//装进去当前用户;
            article.setLikes(relation);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加收藏成功");
                        closeLoading();

                    } else {
                        Log.i("aaaa", "添加收藏失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }

    /** 删除多对多*/
    //填写被当前用户要关注的用户id
    private void clearzan(String articleObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被关注用户并且给上Id
            article.setObjectId(articleObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.remove(user);//装进去当前用户;
            article.setZan(relation);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "取消点赞成功");

                        closeLoading();
                    } else {
                        Log.i("aaaa", "取消点赞失败：" + e.getMessage());
                        closeLoading();
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }
    /**添加多对多文章关注*/
    //填写被当前用户要关注的用户id
    private void addzan(String articleObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被点赞的文章并且给上Id
            article.setObjectId(articleObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user);//装进去当前用户;
            article.setZan(relation);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加点赞成功");
                        closeLoading();

                    } else {
                        Log.i("aaaa", "添加点失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }





    //查询一对多，一个帖子的所有评论
    private void queryALLComment( String articleID){
        openLoading();
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            BmobQuery<Comment> query = new BmobQuery<>();
            Article post = new Article();
            post.setObjectId(articleID);//测试文章1
            query.addWhereEqualTo("article",new BmobPointer(post));
            // query.addWhereEqualTo("author","69489f3e14");
            //包含作者信息
            query.include("user,author,article");
            query.findObjects(new FindListener<Comment>() {
                @Override
                public void done(List<Comment> objects, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "初始化成功！" + objects.size());
                         commentList=objects;
                        Collections.reverse(commentList);//倒序
                               CommentAdaper adapter = new CommentAdaper(ArticleBody.this,commentList,gzlist);//NewAdapterDAO为自定义适配器
                                lsitnew.setAdapter(adapter);
                                closeLoading();
//                        Log.w("aaaa", ""+ user.getUsername());
                    } else {
                        Log.e("aaaa","初始化失败" + e.getMessage());
                    }

                }
            });
            }

    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(ArticleBody.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }


}